package com.lgd.factoryattendance.Activity;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lgd.factoryattendance.Bean.AssemblyGallery;
import com.lgd.factoryattendance.Bean.ElectricalGalleryType;
import com.lgd.factoryattendance.Bean.ProjectManagement;
import com.lgd.factoryattendance.R;
import com.lgd.factoryattendance.Utils.ToastUtils;
import com.lgd.factoryattendance.adapter.ElectricGalleryLiatAdapter;
import com.lgd.factoryattendance.adapter.ElectricGalleryTypeSpinnerAdapter;
import com.lgd.factoryattendance.httpService.API;
import com.lgd.factoryattendance.httpService.httpPort.IStringResponse;
import com.wdeo3601.pdfview.PDFView;

import java.util.ArrayList;
import java.util.List;

public class ElectricGalleryActivity extends BaseActivity implements View.OnClickListener{
    ListView lv_electricGallery;
    List<String> electricGalleryNameList = new ArrayList<>();
    List<String> electricMapNumberList = new ArrayList<>();
    List<String> electricDrawingPathList = new ArrayList<>();
    List<List<String>> electricGalleryListItem = null;
    EditText et_search;
    Button bt_search;
    ImageView iv_delectText, iv_img;
    List<ElectricalGalleryType> electricalGalleryTypeList = null;
    ElectricGalleryTypeSpinnerAdapter typeSpinnerAdapter ;
    Spinner sp_galleryType,sp_drawType;
    Long typeId = null;
    String str_drawType;
    LinearLayout layout_back;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_electric_gallery);
        init();
    }
//    @Override
//    protected void startLockScreenActivity() {
//        Intent intent = new Intent(this, ScreensaverActivity.class);
//        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
//        startActivity(intent);
//    }
    public void init(){
        iv_img = findViewById(R.id.iv_img);
        sp_drawType = findViewById(R.id.sp_drawType);
        sp_drawType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                clearElectricGallery();
                str_drawType = parent.getItemAtPosition(position).toString();
                if (str_drawType.equals("机械")){
                    sp_galleryType.setVisibility(View.GONE);    // 隐藏 类型选择框
                    typeId = 0L;
                }else {
                    sp_galleryType.setVisibility(View.VISIBLE);
                    sp_galleryType.setSelection(0,true);
                }
                AssemblyGallery a = new AssemblyGallery();
                a.setDrawType(str_drawType);
                selectAllByGallery(a);
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        });
        sp_galleryType = findViewById(R.id.sp_galleryType);
        layout_back = findViewById(R.id.layout_back);
        layout_back.setOnClickListener(this);
        iv_delectText = findViewById(R.id.iv_delectText);
        iv_delectText.setOnClickListener(this);
        bt_search = findViewById(R.id.bt_search);
        bt_search.setOnClickListener(this);
        et_search = findViewById(R.id.et_search);
        et_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}
            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().equals("")){
                    iv_delectText.setVisibility(View.GONE);
                    clearElectricGallery();
                    AssemblyGallery a = new AssemblyGallery();
                    a.setDrawType(str_drawType);
                    if (typeId != 0){
                        a.setElectricalGalleryTypeId(typeId);
                    }
                    selectAllByGallery(a);
                }else {
                    iv_delectText.setVisibility(View.VISIBLE);
                }
            }
        });
        lv_electricGallery = findViewById(R.id.lv_electricGallery);

        ElectricalGalleryType e = new ElectricalGalleryType();
        selectGalleryType(e);

//        new Handler().postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                if (electricalGalleryTypeList.size() > 0){
//                    typeSpinnerAdapter = new ElectricGalleryTypeSpinnerAdapter(electricalGalleryTypeList,ElectricGalleryActivity.this);
//                }else {
//                    ToastUtils.warnShowLong(getApplicationContext(),"网络卡顿，请重新进入！！");
//                }
//                sp_galleryType.setAdapter(typeSpinnerAdapter);
//                sp_galleryType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
//                    @Override
//                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//                        typeId = electricalGalleryTypeList.get(position).getElectricalgallerytypeid();
//                    }
//                    @Override
//                    public void onNothingSelected(AdapterView<?> parent) {}
//                });
//            }
//        },666);

    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.bt_search:
//                System.out.println("-- 点击搜索-- 图纸-"+str_drawType+"---iddddddd--"+typeId);
                clearElectricGallery();  // 清除
                String str_search = et_search.getText().toString();
                if (!str_search.equals("15262838595")){
                    AssemblyGallery a = new AssemblyGallery();
                    a.setDrawType(str_drawType);
                    if (typeId != 0){
                        a.setElectricalGalleryTypeId(typeId);
                    }
                    a.setDrawingnumber(str_search);
                    selectAllByGallery(a);
                }else {
                    finishApp();    //  返回桌面
                }
                break;
            case R.id.iv_delectText:  //清除TextView
                et_search.setText("");
                break;
            case R.id.layout_back:
                finish();
                break;
            default:
                break;
        }
    }
    // 获取  电气图库类型
    public void selectGalleryType(ElectricalGalleryType e){
        API.selectGalleryType(e, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                ElectricGalleryActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject j = JSON.parseObject(result);
                        List<ElectricalGalleryType> typeList = new Gson().fromJson(j.getString("data"), new TypeToken<List<ElectricalGalleryType>>(){}.getType() );
                        electricalGalleryTypeList = new ArrayList<>();
                        electricalGalleryTypeList.add(new ElectricalGalleryType(0L,"全部"));
                        if (typeList.size() > 0){
                            for ( ElectricalGalleryType e : typeList) {
                                electricalGalleryTypeList.add(new ElectricalGalleryType(e.getElectricalgallerytypeid(),
                                        e.getElectricaltypename()));
                            }
                        }
                        //
                        setTypeList(electricalGalleryTypeList);
                    }
                });
            }
            @Override
            public void onFail(int statusCode) {}
        });
    }

    public void setTypeList (List<ElectricalGalleryType> list){
        if (list.size() > 0){
            typeSpinnerAdapter = new ElectricGalleryTypeSpinnerAdapter(list,ElectricGalleryActivity.this);
        }else {
            ToastUtils.warnShowLong(getApplicationContext(),"网络卡顿，请重新进入！！");
        }
        sp_galleryType.setAdapter(typeSpinnerAdapter);
        sp_galleryType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                typeId = list.get(position).getElectricalgallerytypeid();
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        });
    }

    // 电气装配图纸
    public void selectAllByGallery(AssemblyGallery a){
        API.selectAllByGallery(a, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                ElectricGalleryActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject j = JSONObject.parseObject(result);
                        List<AssemblyGallery> assemblyGalleryList = new Gson().fromJson(j.getString("data"), new TypeToken<List<AssemblyGallery>>(){}.getType() );
                        if (assemblyGalleryList.size() > 0 ){
                            for (int i = 0; i < assemblyGalleryList.size(); i++) {
                                if (assemblyGalleryList.get(i).getPartsname().equals("") || assemblyGalleryList.get(i).getPartsname() == null){
                                    electricGalleryNameList.add("暂无名称");
                                }else {
                                    electricGalleryNameList.add(assemblyGalleryList.get(i).getPartsname());
                                }
                                electricMapNumberList.add(assemblyGalleryList.get(i).getDrawingnumber());
                                electricDrawingPathList.add(assemblyGalleryList.get(i).getDrawingpath());
                            }
                        }
                        electricGalleryDate();
                    }
                });
            }
            @Override
            public void onFail(int statusCode) {}
        });
    }
    // 清除 图号数据
    public void clearElectricGallery(){
        if (electricGalleryListItem != null){
            electricGalleryListItem.clear();
            electricGalleryNameList.clear();
            electricMapNumberList.clear();
            electricDrawingPathList.clear();
            ElectricGalleryLiatAdapter adapter = new ElectricGalleryLiatAdapter(ElectricGalleryActivity.this,electricGalleryListItem);
            lv_electricGallery.setAdapter(adapter);
        }
    }
    // listview 图库 数据
    public void electricGalleryDate(){
        electricGalleryListItem = new ArrayList<>();
        for (int i = 0; i < electricMapNumberList.size(); i++) {
            List<String> electricGalleryShowItem = new ArrayList<>();
            electricGalleryShowItem.add(electricGalleryNameList.get(i));
            electricGalleryShowItem.add(electricMapNumberList.get(i));
            electricGalleryShowItem.add(electricDrawingPathList.get(i));
            electricGalleryListItem.add(electricGalleryShowItem);
        }
        if (electricGalleryListItem == null || electricGalleryListItem.isEmpty()) {
            ToastUtils.warnShowLong(getApplicationContext(),"暂无数据！！！");
            iv_img.setVisibility(View.VISIBLE);
            lv_electricGallery.setVisibility(View.GONE);

        }else {
            iv_img.setVisibility(View.GONE);
            lv_electricGallery.setVisibility(View.VISIBLE);
            ElectricGalleryLiatAdapter adapter = new ElectricGalleryLiatAdapter(ElectricGalleryActivity.this,electricGalleryListItem);
            lv_electricGallery.setAdapter(adapter);
            lv_electricGallery.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    String path = electricGalleryListItem.get(position).get(2);
                    showPdfInDialog(path);
                }
            });
        }
    }
    Dialog dialog;
    // dialog 查看 PDF
    private void showPdfInDialog(String pdfPath) {
        dialog = new Dialog(ElectricGalleryActivity.this);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.dialog_pdf_viewer);
        dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent); // 设置Dialog背景透明
        dialog.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT); // 设置Dialog大小
        dialog.getWindow().setGravity(Gravity.CENTER);
        dialog.show();
        //  PDF 控件设置
        PDFView pdfView = dialog.findViewById(R.id.pdfView);
        pdfView.isCanZoom(true);
        pdfView.setMaxScale(10f);
        pdfView.showPdfFromUrl(pdfPath);
        LinearLayout layout_back = dialog.findViewById(R.id.layout_back);
        layout_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }

    // 点击键盘外 关闭软键盘
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }
    public  boolean isShouldHideInput(View v, MotionEvent event) {
        if ((v instanceof EditText)) {
            int[] leftTop = { 0, 0 };
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

    private void finishApp(){
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addCategory(Intent.CATEGORY_HOME);
        startActivity(intent);
    }
}